package com.js.foodordersystem.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.js.foodordersystem.entity.User;
import com.js.foodordersystem.service.UserService;
import com.js.foodordersystem.util.JwtUtil;
import com.js.foodordersystem.util.Result;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 存储用户信息(User)表控制层
 *
 * @author makejava
 * @since 2025-01-09 10:52:56
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @Value("${default-password}")
    private String defaultPassword;

    /**
     * 分页查询
     *
     * @param user  筛选条件
     * @param limit 分页对象
     * @param page  分页对象
     * @return 查询结果
     */
    @GetMapping("findAll")
    public Result findAll(User user, Integer limit, Integer page) {
        if (limit == null || page == null) {
            return Result.failure("limit和page不能为空");
        }
        return userService.selectAll(user, limit, page);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("getById")
    public Result getById(Long id) {
        return Result.success(this.userService.getById(id));
    }

    /**
     * 通过token查询单条数据
     *
     * @return 单条数据
     */
    @GetMapping("getOneByToken")
    public Result getOneByToken(HttpServletRequest request) {
        Long id = JwtUtil.getUserIdFromToken(request.getHeader("token"));
        return Result.success(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public Result add(@RequestBody User user) {
        //判断是否为空
        if (user == null) {
            return Result.failure("参数不能为空");
        }
        if (user.getPassword() == null){
            user.setPassword(defaultPassword);
        }

        if (!StringUtils.hasLength(user.getAvatar())) {
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }

        //判断账号是否已经存在
        if (this.userService.count(new QueryWrapper<User>().eq("username", user.getUsername()).eq("type", user.getType())) > 0) {
            return Result.failure("账号已存在");
        }
        if (this.userService.save(user)) {
            return Result.success("添加成功");
        }
        return Result.failure("添加失败");
    }

    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @PostMapping("edit")
    public Result edit(@RequestBody User user) {
        //判断是否为空
        if (user == null) {
            return Result.failure("参数不能为空");
        }
        //判断账号是否已经存在
        if (this.userService.count(new QueryWrapper<User>().eq("username", user.getUsername()).eq("type", user.getType()).ne("user_id", user.getUserId())) > 0) {
            return Result.failure("账号已存在");
        }
        if (this.userService.updateById(user)) {
            return Result.success("修改成功");
        }
        return Result.failure("修改失败");
    }

    @PostMapping("editByToken")
    public Result editByToken(@RequestBody User user, HttpServletRequest request) {
        //判断是否为空
        if (user == null) {
            return Result.failure("参数不能为空");
        }
        Long id = JwtUtil.getUserIdFromToken(request.getHeader("token"));
        user.setUserId(id);
        //判断账号是否已经存在
        if (this.userService.count(new QueryWrapper<User>().eq("username", user.getUsername()).eq("type", user.getType()).ne("user_id", user.getUserId())) > 0) {
            return Result.failure("账号已存在");
        }
        if (this.userService.updateById(user)) {
            return Result.success("修改成功");
        }
        return Result.failure("修改失败");
    }

    /**
     * 删除数据
     *
     * @return 删除是否成功
     */
    @PostMapping("delete")
    public Result deleteById(@RequestBody JSONObject data) {
        //判断id是否为空
        Long id = data.getLong("userId");
        if (id == null) {
            return Result.failure("id不能为空");
        }

        if (this.userService.removeById(id)) {
            return Result.success("删除成功");
        }
        return Result.failure("删除失败");
    }

    @PostMapping("login")
    public Result login(@RequestBody User user, HttpServletRequest request) {
        //判断是否为空
        if (user == null) {
            return Result.failure("参数不能为空");
        }

        //根据账号和角色进行查找
        QueryWrapper<User> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", user.getUsername());
        usersQueryWrapper.eq("type", user.getType());
        User one = userService.getOne(usersQueryWrapper);

        if (one == null) {
            return Result.failure("账号不存在,请先注册");
        }

        if (!one.getPassword().equals(user.getPassword())) {
            return Result.failure("密码错误,请重新输入");
        }
        String token = JwtUtil.generateToken(one.getUserId(), JwtUtil.getClientIpAddress(request), JwtUtil.getUserAgent(request));
        return Result.success("登录成功", token);
    }

    @PostMapping("register")
    public Result register(@RequestBody User user) {
        //判断是否为空
        if (user == null) {
            return Result.failure("参数不能为空");
        }

        //根据账号和角色进行查找
        QueryWrapper<User> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", user.getUsername());
        usersQueryWrapper.eq("type", user.getType());
        User one = userService.getOne(usersQueryWrapper);

        if (one != null) {
            return Result.failure("账号已经注册，请直接登录，或者更换账号注册！");
        }

        if (!StringUtils.hasLength(user.getAvatar())) {
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }
        userService.save(user);
        return Result.success("注册成功");
    }
}

